package com.yantong.utils;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.text.ParseException;

public class MD5Utils {
	private static final String SALT = "1qazxsw2";

	private static final String ALGORITH_NAME = "md5";

	private static final int HASH_ITERATIONS = 2;

	private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5",
			"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

	private static MessageDigest md5;

	/**
	 * 32位MD5加密的大写字符串
	 *
	 * @param s
	 * @return
	 */
	public final static String MD5(String s) {
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'A', 'B', 'C', 'D', 'E', 'F' };
		try {
			byte[] btInput = s.getBytes();
			// 获得MD5摘要算法的 MessageDigest 对象
			MessageDigest mdInst = MessageDigest.getInstance("MD5");
			// 使用指定的字节更新摘要
			mdInst.update(btInput);
			// 获得密文
			byte[] md = mdInst.digest();
			// 把密文转换成十六进制的字符串形式
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	/**
	 * MD5加密转大写
	 */
	public static String MD5EncodeInUppercase(String beforeEncrypted,String charset) {
		String resultString="";
		try {
			md5=MessageDigest.getInstance("MD5");
			if(charset==null||charset.equals("")) {
				resultString = byteArrayToHexString(md5.digest(beforeEncrypted.getBytes()));
			}else {
				resultString = byteArrayToHexString(md5.digest(beforeEncrypted.getBytes(charset)));
			}

		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return resultString.toUpperCase();
	}

	public static String encrypt(String pswd) {
		String newPassword = new SimpleHash(ALGORITH_NAME, pswd, ByteSource.Util.bytes(SALT), HASH_ITERATIONS).toHex();
		return newPassword;
	}

	public static String encrypt(String username, String pswd) {
		String newPassword = new SimpleHash(ALGORITH_NAME, pswd, ByteSource.Util.bytes(username + SALT),
				HASH_ITERATIONS).toHex();
		return newPassword;
	}

	/**
	 * 签名字符串
	 * @param text 需要签名的字符串
	 * @param key 密钥
	 * @param input_charset 编码格式
	 * @return 签名结果
	 */
	public static String sign(String text, String key, String input_charset) {
		text = text + key;
		//System.out.println(text);
		return DigestUtils.md5Hex(getContentBytes(text, input_charset)).toUpperCase();
	}
	/**
	 * @param content
	 * @param charset
	 * @return
	 * @throws SignatureException
	 * @throws UnsupportedEncodingException
	 */
	private static byte[] getContentBytes(String content, String charset) {
		if (charset == null || "".equals(charset)) {
			return content.getBytes();
		}
		try {
			return content.getBytes(charset);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
		}
	}

	public static String MD5Encode(String origin, String charsetname) {
		String resultString = null;
		try {
			resultString = new String(origin);
			MessageDigest md = MessageDigest.getInstance("MD5");
			if (charsetname == null || "".equals(charsetname)){
				resultString = byteArrayToHexString(md.digest(resultString
						.getBytes()));
			} else{
				resultString = byteArrayToHexString(md.digest(resultString
						.getBytes(charsetname)));
			}

		} catch (Exception exception) {
		}
		return resultString;
	}

	/**
	 * 字节数组转16进制字符串
	 */
	private static String byteArrayToHexString(byte b[]) {
		StringBuffer resultSb = new StringBuffer();
		for (int i = 0; i < b.length; i++) {
			resultSb.append(byteToHexString(b[i]));
		}
		return resultSb.toString();
	}

	private static String byteToHexString(byte b) {
		int n = b;
		if (n < 0) {
			n += 256;
		}
		int d1 = n / 16;
		int d2 = n % 16;
		return hexDigits[d1] + hexDigits[d2];
	}

	public static String get32Md5(String data){
		String result = "";
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(data.getBytes());
			byte b[] = md.digest();
			int i;
			StringBuffer buf = new StringBuffer("");
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0) {
					i += 256;
				}
				if (i < 16) {
					buf.append("0");
				}
				buf.append(Integer.toHexString(i));
			}
			result = buf.toString();
//            System.out.println("MD5(" + data + ",32小写) = " + result);
//            System.out.println("MD5(" + data + ",32大写) = " + result.toUpperCase());
//            System.out.println("++++++++++++++++++++++++各位大哥借过+++++++++++++++++++++++");
//            System.out.println("MD5(" + data + ",16小写) = " + buf.toString().substring(8, 24));
//            System.out.println("MD5(" + data + ",16大写) = " + buf.toString().substring(8, 24).toUpperCase());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return result;
	}



	public static void main(String[] args) throws ParseException {
//
		System.out.println(MD5Utils.encrypt("18684679209", "123456"));
//		System.out.println(UUID.randomUUID());

//		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMM");
//		Date start = simpleDateFormat.parse("201801");
//		Calendar calendar =Calendar.getInstance();
//		calendar.setTime(start);
//		calendar.add(Calendar.DAY_OF_MONTH, 1);
//
//		System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime()));
//		calendar.set(Calendar.DAY_OF_MONTH,1);
//		System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime()));
//		System.out.println(calendar.get(Calendar.DAY_OF_MONTH));
//
//
//		System.out.println((UUID.randomUUID().toString()));

	}

}
